//
//  MessageViewController.m
//  BQDemo
//
//  Created by YangShuai on 16/5/19.
//  Copyright © 2016年 ys. All rights reserved.
//

#import "InputViewController.h"
#import "JRMasonry.h"
#import "UIColor+Hex.h"
#import "DataProcess.h"
#import <sys/utsname.h>
@interface InputViewController ()<UITextViewDelegate>{
    UIView* _containerView;
    UIView* _blueView;
    UIView* _clearView;
    NSString* _originalMessage;
}
@property(nonatomic,copy)MessageDoneBlock myMessageDoneBlock;
@property(nonatomic,strong)UITextView* textView;
@property(nonatomic,strong)UILabel* surplusWordsLabel;
@property(nonatomic,strong)UIButton* doneButton;
@property(nonatomic,strong)UILabel* placeHolder;
@end

@implementation InputViewController

- (instancetype)init
{
    self = [super init];
    if (self) {
        _tapEmptyType = TapEmptyType_Finish;
    }
    return self;
}


- (void)viewDidLoad {
    self.title = nil;
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    //keyBoardEvent
    [self addContainerView];
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
}

-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    [_textView becomeFirstResponder];
}


-(void)showMessageVCOnParentVC:(UIViewController*)parentVC OriginalMessage:(NSString*)originalMessage MessageDone:(MessageDoneBlock)messageDone{
    self.myMessageDoneBlock = messageDone;
    _originalMessage = originalMessage;
    [parentVC addChildViewController:self];
    [parentVC.view addSubview:self.view];
    [self didMoveToParentViewController:parentVC];
    
}
//添加灰色背景
-(void)addContainerView{
    _containerView = [[UIView alloc] init];
    _containerView.backgroundColor = [[UIColor grayColor] colorWithAlphaComponent:0];
    UITapGestureRecognizer* tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    [_containerView addGestureRecognizer:tap];
    [self.view addSubview:_containerView];
    [_containerView JRMAS_makeConstraints:^(JRMASConstraintMaker *make) {
        make.edges.JRMAS_equalTo(self.view);
    }];
    [UIView animateWithDuration:0.3 animations:^{
        _containerView.backgroundColor = [[UIColor grayColor] colorWithAlphaComponent:0.3];
    }];
    [self subViewsLayout];
}

-(void)subViewsLayout{
    //蓝色背景
    _blueView = [[UIView alloc] init];
    _blueView.backgroundColor = [[UIColor colorWithHexString:@"#6198E4"] colorWithAlphaComponent:0.8];
    [_containerView addSubview:_blueView];
    [_blueView JRMAS_makeConstraints:^(JRMASConstraintMaker *make) {
        make.top.JRMAS_equalTo(_containerView.JRMAS_bottom).offset(0);
        make.centerX.JRMAS_equalTo(0);
        make.bottom.JRMAS_equalTo(0);
        make.width.JRMAS_equalTo(self.view);
    }];
    //透明容器
    _clearView = [[UIView alloc] init];
    _clearView.backgroundColor = [UIColor clearColor];
    [_blueView addSubview:_clearView];
    [_clearView JRMAS_makeConstraints:^(JRMASConstraintMaker *make) {
        make.width.JRMAS_equalTo(_blueView);
        make.height.JRMAS_equalTo(0);
        make.top.JRMAS_equalTo(0);
        make.centerX.JRMAS_equalTo(0);
    }];
    //输入框
    _textView = [[UITextView alloc] init];
    _textView.keyboardType = UIKeyboardAppearanceDefault;
    _textView.text = _originalMessage;
    _textView.delegate = self;
    _textView.font = [UIFont systemFontOfSize:22];
    if ([self isiPhone]) {
        _textView.font = [UIFont systemFontOfSize:18];
    }
    _textView.layer.cornerRadius = 10;
    [_clearView addSubview:_textView];
    [_textView JRMAS_makeConstraints:^(JRMASConstraintMaker *make) {
        make.left.JRMAS_equalTo(10);
        make.top.JRMAS_equalTo(12);
        make.right.JRMAS_equalTo(-10);
        make.bottom.JRMAS_equalTo(-60);
    }];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textViewChanged:) name:UITextViewTextDidChangeNotification object:_textView];
    //placeHolder
    _placeHolder = [[UILabel alloc] init];
    _placeHolder.font = [UIFont systemFontOfSize:22];
    if ([self isiPhone]) {
        _placeHolder.font = [UIFont systemFontOfSize:18];
    }
    _placeHolder.textColor = [UIColor lightGrayColor];
    _placeHolder.text = NSLocalizedStringFromTable(@"placeHolderText", @"InputLocalizable", @"");
    [_textView addSubview:_placeHolder];
    [_placeHolder JRMAS_makeConstraints:^(JRMASConstraintMaker *make) {
        make.left.JRMAS_equalTo(8);
        make.top.JRMAS_equalTo(8);
    }];
    //剩余字数
    _surplusWordsLabel = [[UILabel alloc] init];
    _surplusWordsLabel.textColor = [UIColor whiteColor];
    _surplusWordsLabel.text = [NSString stringWithFormat:NSLocalizedStringFromTable(@"surplusWordsLimmit", @"InputLocalizable", @""),@(200 -_originalMessage.length)];
    [_clearView addSubview:_surplusWordsLabel];
    [_surplusWordsLabel JRMAS_makeConstraints:^(JRMASConstraintMaker *make) {
        make.left.JRMAS_equalTo(10);
        make.top.JRMAS_equalTo(_textView.JRMAS_bottom).offset(20);
    }];
    //完成btn
    _doneButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [_doneButton setTitle:NSLocalizedStringFromTable(@"done", @"InputLocalizable", @"") forState:UIControlStateNormal];
    [_doneButton addTarget:self action:@selector(messageDoneAction:) forControlEvents:UIControlEventTouchUpInside];
    _doneButton.titleLabel.font = [UIFont boldSystemFontOfSize:25];
    if ([self isiPhone]) {
        _doneButton.titleLabel.font = [UIFont boldSystemFontOfSize:22];
    }
    [_clearView addSubview:_doneButton];
    [_doneButton JRMAS_makeConstraints:^(JRMASConstraintMaker *make) {
        make.centerY.JRMAS_equalTo(_surplusWordsLabel.JRMAS_centerY);
        make.right.JRMAS_equalTo(-10);
    }];
}
//完成点击事件
-(void)messageDoneAction:(UIButton*)button{
    [self dissmissMessageVC];
}
//隐藏键盘
-(void)tapAction:(UITapGestureRecognizer*)tap{
    if (_tapEmptyType == TapEmptyType_KeyBoard) {
        [_textView resignFirstResponder];
        if (_textView.text.length == 0) {
            _placeHolder.hidden = NO;
        }
    }else if (_tapEmptyType == TapEmptyType_Finish){
        [self dissmissMessageVC];
    }
}

-(void)dissmissMessageVC{
    if (_myMessageDoneBlock) {
        if (_textView.isFirstResponder) {
            _myMessageDoneBlock(_textView.text);
        }else{
            _myMessageDoneBlock(_originalMessage);
        }
    }
    [UIView animateWithDuration:0.3 animations:^{
        _containerView.backgroundColor = [[UIColor grayColor] colorWithAlphaComponent:0];
    }];
    [_textView resignFirstResponder];
    [self willMoveToParentViewController:nil];
    [self.view removeFromSuperview];
    [self removeFromParentViewController];
}

- (void)keyboardWillShow:(NSNotification*)notification{
    _textView.text = _originalMessage;
    _placeHolder.hidden = YES;
    if (_textView.text.length == 0) {
        _placeHolder.hidden = NO;
    }
    _textView.scrollEnabled = YES;
    NSDictionary* userInfo = [notification userInfo];
    NSValue* aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyBoardRect = [aValue CGRectValue];
    NSValue* animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSTimeInterval animationDuration;
    [animationDurationValue getValue:&animationDuration];
    [_blueView JRMAS_updateConstraints:^(JRMASConstraintMaker *make) {
        make.top.JRMAS_equalTo(_containerView.JRMAS_bottom).offset(-280 - keyBoardRect.size.height);
    }];
    [_clearView JRMAS_updateConstraints:^(JRMASConstraintMaker *make) {
        make.height.JRMAS_equalTo(280);
    }];
    if ([self isiPhone]) {
        [_blueView JRMAS_updateConstraints:^(JRMASConstraintMaker *make) {
            make.top.JRMAS_equalTo(_containerView.JRMAS_bottom).offset(-180 - keyBoardRect.size.height);
        }];
        [_clearView JRMAS_updateConstraints:^(JRMASConstraintMaker *make) {
            make.height.JRMAS_equalTo(180);
        }];
    }
    [UIView animateWithDuration:animationDuration animations:^{
        [_blueView layoutIfNeeded];
    }];
}

- (void)keyboardWillHide:(NSNotification*)notification{
    _originalMessage = _textView.text;
    _textView.text = nil;
    _placeHolder.hidden = NO;
    _textView.scrollEnabled = NO;
    NSDictionary* userInfo = [notification userInfo];
    NSValue* animationDurationValue = [userInfo objectForKey:UIKeyboardAnimationDurationUserInfoKey];
    NSTimeInterval animationDuration;
    [animationDurationValue getValue:&animationDuration];
    [_blueView JRMAS_updateConstraints:^(JRMASConstraintMaker *make) {
        make.top.JRMAS_equalTo(_containerView.JRMAS_bottom).offset(-110);
    }];
    [_clearView JRMAS_updateConstraints:^(JRMASConstraintMaker *make) {
        make.height.JRMAS_equalTo(110);
    }];
    [UIView animateWithDuration:animationDuration animations:^{
        [_blueView layoutIfNeeded];
    }];
}

#pragma mark - UITextViewDelegate
//字数限制
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    NSString * toBeString = [_textView.text stringByReplacingCharactersInRange:range withString:text];
    if (toBeString.length > 0) {
        if (toBeString.length > 200) {
            return NO;
        }
    }
    return YES;
}

-(void)textViewDidChange:(UITextView *)textView{
    if (textView.text.length <= 200 && textView.markedTextRange == nil) {
        _surplusWordsLabel.text = [NSString stringWithFormat:NSLocalizedStringFromTable(@"surplusWordsLimmit", @"InputLocalizable", @""),@(200 - textView.text.length)];
    }else if (textView.text.length > 200){
        _surplusWordsLabel.text = [NSString stringWithFormat:NSLocalizedStringFromTable(@"surplusWordsLimmit", @"InputLocalizable", @""),@(0)];
    }
}

//观察者方法
- (void)textViewChanged:(id)sender
{
    NSNotification* noti = (NSNotification*)sender;
    UITextView* textView = noti.object;
    if (textView.text.length  > 0) {
        _placeHolder.hidden = YES;
    }else{
        _placeHolder.hidden = NO;
    }
    
    if (_textView.text.length > 200) {
        if ([DataProcess iOS7_low]) {
            [_textView deleteBackward];
        }else {
            _textView.text = [_textView.text substringWithRange:NSMakeRange(0, 200)];
        }
        
    }
}
-(BOOL)isiPhone{
    NSString* tlDevice = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleTLDevice"];
    if (tlDevice.length <= 0) {
        tlDevice = [self machineName];
    }
    if (tlDevice) {
        if ([tlDevice hasPrefix:@"iPhone"] || [tlDevice hasPrefix:@"iPod"]) {
            return YES;
        }
        if ([tlDevice hasPrefix:@"iPad"]) {
            return NO;
        }
    }
    return YES;
}
-(NSString*) machineName
{
    struct utsname systemInfo;
    uname(&systemInfo);
    NSString* deviceString = [NSString stringWithCString:systemInfo.machine
                                                encoding:NSUTF8StringEncoding];
    NSString* deviceModel = [[UIDevice currentDevice] model];
    if ([deviceString hasPrefix:deviceModel]) {
        return deviceString;
    }
    return deviceModel;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
